import axios from 'axios';  //引入axios
import { Message } from 'element-ui'
axios.interceptors.request.use(config => {
  if (localStorage.token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.Authorization = `${localStorage.token}`;
  }
  return config;
}, err => {
  Message.error({ message: '请求超时!' });
})
axios.interceptors.response.use(data => {
  if (data.data.code && data.data.code != '200') {
    Message.error({ message: data.data.message});
  }
  return data.data;
}, err => {
  if(err.response!=null){
    if (err.response.status == '504' || err.response.status == '404') {
      Message.error({message: '找不到资源呢，亲'});
    } else if (err.response.data.status == '403') {
      Message.error({message: '权限不足,请联系管理员!'});
    } else if (err.response.data.status == '401') {
      Message.error({message: err.response.data.message});
    } else {
      Message.error({message: err.response.data.message});
    }
  }else{
    Message.error({message: '哦豁，服务器走丢了!'});
  }

})
// let base = 'http://39.101.170.85:9005';
let base = 'http://127.0.0.1:8082';
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'application/json'
    }
  });
}
export const putRequest = (url, params) => {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'application/json'
    }
  });
}
export const deleteRequest = (url) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`
  });
}
export const getRequest = (url) => {
  return axios({
    method: 'get',
    url: `${base}${url}`
  });
}
